<template>
  <div class="app">
    <div class="head">
      <h1 class="title">诊断管理</h1>
    </div>
    <el-main class="main">
      <div>
        <div class="buttons">
          <el-button type="success" @click="newDiagnosis">
            <el-icon class="el-icon--left"><Edit /></el-icon>新增
          </el-button>
          <el-button-group>
            <el-button :type="currentFilterStatus === 'all' ? 'primary' : 'info'" @click="setFilterStatus('all')">全部</el-button>
            <el-button :type="currentFilterStatus === '新开单' ? 'primary' : 'info'" @click="setFilterStatus('新开单')">新开单</el-button>
            <el-button :type="currentFilterStatus === '进行中' ? 'primary' : 'info'" @click="setFilterStatus('进行中')">进行中</el-button>
            <el-button :type="currentFilterStatus === '已完成' ? 'primary' : 'info'" @click="setFilterStatus('已完成')">已完成</el-button>
            <el-button :type="currentFilterStatus === '已暂停' ? 'primary' : 'info'" @click="setFilterStatus('已暂停')">已暂停</el-button>
            <el-button :type="currentFilterStatus === '已取消' ? 'primary' : 'info'" @click="setFilterStatus('已取消')">已取消</el-button>
          </el-button-group>
        </div>
        <el-table :data="filtereddiagnosis" style="width: 100%">
          <el-table-column prop="title" label="标题"></el-table-column>
          <el-table-column prop="patientName" label="患者"></el-table-column>
          <el-table-column prop="department" label="会诊科室"></el-table-column>
          <el-table-column prop="bedNumber" label="住院床号"></el-table-column>
          <el-table-column prop="responsiblePerson" label="负责人"></el-table-column>
          <el-table-column prop="amount" label="金额"></el-table-column>
          <el-table-column prop="time" label="时间"></el-table-column>
          <el-table-column prop="medicine" label="药品"></el-table-column>
          <el-table-column prop="diagnosisStatus" label="状态"></el-table-column>
          <el-table-column prop="content" label="描述"></el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <el-button class="operate-buttons" link @click="edit(scope.row)" type="primary" size="small">编辑</el-button>
              <el-button class="operate-buttons" link @click="deleteDiagnosis(scope.row)" type="danger" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <!-- 新建诊断单对话框 -->
    <el-dialog v-model="dialogFormVisible" title="新建诊断单" width="500">
      <div class="diagnosisForm">
        <el-form :model="form" label-width="120px" class="demo-form">
          <el-form-item label="标题">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="患者">
            <el-input v-model="form.patientName" disabled>
              <template #append>
                <el-button @click="searchPatient"><el-icon class="el-icon--left"><Search /></el-icon>查找</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="住院床号">
            <el-input v-model="form.bedNumber"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.diagnosisStatus" placeholder="请选择状态">
              <el-option label="新开单" value="新开单"></el-option>
              <el-option label="进行中" value="进行中"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="已暂停" value="已暂停"></el-option>
              <el-option label="已取消" value="已取消"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="诊断">
            <el-input type="textarea" v-model="form.content" :rows="10"></el-input>
          </el-form-item>
          <el-form-item label="药品">
            <el-input v-model="form.medicine"></el-input>
          </el-form-item>
          <el-form-item label="金额">
            <el-input v-model="form.amount" type="number"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 查找患者对话框 -->
    <el-dialog v-model="patientDialogVisible" title="查找患者" width="600">
      <el-input v-model="patientSearchQuery" placeholder="请输入患者姓名进行搜索"></el-input>
      <el-table :data="filterPatients" style="width: 100%" @row-click="selectPatient">
        <el-table-column prop="patientId" label="病人ID"></el-table-column>
        <el-table-column prop="patientName" label="姓名"></el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button @click="selectPatient(scope.row)" type="primary" size="small">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Search } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  data() {
    return {
      diagnosis: [],
      dialogFormVisible: false,
      patientDialogVisible: false,
      currentFilterStatus: 'all',
      form: {
        title: '',
        patientName: '',
        department: '',
        bedNumber: '',
        responsiblePerson: '',
        diagnosisStatus: '新开单',
        amount: 0,
        medicine: '',
        content: '',
        patientId: '',
        doctorName: '',
        doctorId: this.$store.state.id
      },
      currentDoctorInfo: {},
      patients: [],
      patientSearchQuery: ''
    }
  },
  computed: {
    filterPatients() {
      if (!Array.isArray(this.patients)) {
        return []
      }
      return this.patients.filter(patient => patient.patientName.indexOf(this.patientSearchQuery) !== -1)
    },
    filtereddiagnosis() {
      if (!Array.isArray(this.diagnosis)) {
        return []
      }
      if (this.currentFilterStatus === 'all') {
        return this.diagnosis
      }
      return this.diagnosis.filter(diagnosis => diagnosis.diagnosisStatus === this.currentFilterStatus)
    }
  },
  methods: {
    fetchDoctorInfo() {
      axios.get(`http://localhost:8085/api/doctor/id/${this.$store.state.id}`)
        .then(response => {
          this.currentDoctorInfo = response.data.data
          // 更新表单中的默认值
          this.form.department = this.currentDoctorInfo.speciality
          this.form.doctorName = this.currentDoctorInfo.name
        })
        .catch(error => {
          console.error('Error fetching doctor info:', error)
        })
    },
    fetchData() {
      axios.get('http://localhost:8085/api/diagnosis/getByDoctorId', {
        params: {
          doctorId: this.$store.state.id
        }
      })
      .then(response => {
        if(response.data.code == 1){
          this.diagnosis = response.data.data;
          return;
        }
      })
      .catch(error => {
        console.error('Error fetching diagnosis:', error)
        this.diagnosis = []
      })
    },
    fetchPatients() {
      axios.get('http://localhost:8085/api/appointment/getByDoctorId', {
        params: {
          doctorId: this.$store.state.id
        }
      })
      .then(response => {
        if (Array.isArray(response.data)) {
          this.patients = response.data
        } else if (response.data && Array.isArray(response.data.patients)) {
          this.patients = response.data.patients
        } else {
          console.error('Unexpected response format:', response.data)
          this.patients = []
        }
      })
      .catch(error => {
        console.error('Error fetching patients:', error)
        this.patients = []
      })
    },
    setFilterStatus(status) {
      this.currentFilterStatus = status
    },
    edit(row) {
      this.form = { ...row }
      this.dialogFormVisible = true
    },
    newDiagnosis() {
      this.form = {
        title: '',
        patientName: '',
        department: this.currentDoctorInfo.speciality,
        bedNumber: '',
        responsiblePerson: this.$store.state.userName,
        diagnosisStatus: '新开单',
        amount: 0,
        medicine: '',
        content: '',
        patientId: '',
        doctorName: this.currentDoctorInfo.name,
        doctorId: this.$store.state.id
      }
      this.dialogFormVisible = true
    },
    deleteDiagnosis(row) {
      ElMessageBox.confirm('此操作将永久删除该诊断, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.diagnosis.indexOf(row)
        if (index !== -1) {
          this.diagnosis.splice(index, 1)
        }
        axios.delete('http://localhost:8085/api/diagnosis/'+ row.diagnosisId
        ).then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          ElMessage.error('删除失败')
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitForm() {
      axios.post('http://localhost:8085/api/diagnosis', this.form)
        .then(response => {
          ElMessage({
            message: '新建诊断成功',
            type: 'success'
          })
          this.dialogFormVisible = false
          this.fetchData()
        })
        .catch(() => {
          ElMessage.error('新建诊断失败')
        })
    },
    searchPatient() {
      this.patientDialogVisible = true
      this.fetchPatients()
    },
    selectPatient(row) {
      this.form.patientName = row.patientName
      this.form.patientId = row.patientId
      this.patientDialogVisible = false
    }
  },
  created() {
    this.fetchDoctorInfo()
    this.fetchData()
  }
}
</script>

<style>
.title {
  text-align: left;
  margin: 0 0 20px 0;
}
.buttons {
  display: flex;
  justify-content: left;
  padding: 10px;
  border-top: 5px solid gray;
}
.main {
  padding: 0px;
  border: 1px solid gray;
  border-radius: 5px;
}
.el-button {
  width: auto;
  padding: 10px;
  border-radius: 6px;
  font-weight: bold;
}
.el-button-group {
  margin-left: auto;
}
.buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.buttons .el-button-group {
  margin-left: auto;
}

.operate-buttons {
  margin: 0;
}
</style>
